package com.xyh.eduservice.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyh.commonutils.JwtUtils;
import com.xyh.commonutils.R;
import com.xyh.commonutils.ordervo.CourseWebVoOrder;
import com.xyh.eduservice.client.OrdersClient;
import com.xyh.eduservice.entity.EduCourse;
import com.xyh.eduservice.entity.chapter.ChapterVo;
import com.xyh.eduservice.entity.frontvo.CourseQueryVo;
import com.xyh.eduservice.entity.frontvo.CourseWebVo;
import com.xyh.eduservice.service.EduChapterService;
import com.xyh.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
//@CrossOrigin
public class CourseFrontController {

    @Resource
    private OrdersClient ordersClient;

    @Resource
    private EduCourseService courseService;

    @Resource
    private EduChapterService chapterService;

    //条件查询带分页
    @PostMapping("/getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable("page") Long page, @PathVariable("limit") Long limit,
                                @RequestBody(required = false) CourseQueryVo courseQueryVo){
        Page<EduCourse> coursePage = new Page<>(page, limit);
        Map<String,Object> map = courseService.getCourseFrontList(coursePage,courseQueryVo);
        return R.ok().data(map);
    }

    //课程详情的方法
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);
        //根据课程id查询章节和小节
        List<ChapterVo> chapterVoList = chapterService.getChapterVideoByCourseId(courseId);

        //根据课程id 和 用户id 查询当前课程是否已经支付过
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean buyCourse = ordersClient.isBuyCourse(courseId, memberId);
        return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVoList).data("isBuy",buyCourse);
    }

    //根据课程id查询课程信息
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id) {
        CourseWebVo courseInfo = courseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(courseInfo,courseWebVoOrder);
        return courseWebVoOrder;
    }
}
